<template>
  <div class="page">

    <!-- 单页 开始 -->
    <div class="single_page">
      <img src="@/assets/images/pdf/snow.png" alt="" class="snow" />
      <div class="inner_page">
        <!-- logo 开始 -->
        <div class="logo_top plr40">
          <img src="@/assets/images/pdf/logo.png" class="logo" alt="" />
          <div class="logo_desc">
            <p>邦正口腔 | 互联网口腔健康服务平台</p>
            <p class="p2">专注于提升全民口腔健康水平</p>
          </div>
        </div>
        <!-- logo end -->

        <!-- 标题 开始 -->
        <div class="title_box plr40">
          <div>
            <img src="@/assets/images/pdf/text.png" class="img" alt="">
          </div>
          <div>
            <img src="@/assets/images/pdf/report.png" class="img_name" alt="">
          </div>
        </div>
        <!-- 标题 end -->

        <!-- 用户信息 开始 -->
        <div class="user_info plr40">
          <div class="user">
            <span class="name">{{reportInfo.name}}</span>
            <span>/{{reportInfo.gender == 1?'先生':'女士'}}</span>
          </div>
          <div class="time">
            {{showTime(reportInfo.createdDate)}}
          </div>
        </div>
        <!-- 用户信息 end -->

        <!-- 说明 开始 -->
        <div class="desc_wrap plr40">
          本报告基于您的口腔全景影像生成，部分问题需面诊方可确认，无法给出评估；该报告仅作为治疗建议的放射数据参考印象，不具有病史同等效
        </div>
        <!-- 说明 end -->

        <!-- 页脚 开始 -->
        <div class="footer">
          <img src="@/assets/images/pdf/footer.png" alt="">
        </div>
        <!-- 页脚 end -->
      </div>
    </div>
    <!-- 单页 end -->

    <!-- 第二页 开始 -->
    <div class="single_page">

      <div class="inner_page plr40">

        <!-- 面包屑 开始 -->
        <bread-crumbs :name="reportInfo.name"></bread-crumbs>
        <!-- 面包屑 end -->

        <!-- 得分 开始 -->
        <div class="score_box">
          <div class="left">
            <p class="p1">您的口腔健康得分</p>
            <p class="p2">Oral Health Score</p>
          </div>
          <div class="right">
            <span class="num">{{reportInfo.oralCavityScore}}</span>
            <span>分</span>
          </div>
        </div>
        <!-- 得分 end -->
        <!-- 级别 开始 -->
        <div class="level_box">
          <div class="cell" :class="level == item.id?'active':''" v-for="(item,index) in levelList" :key="`level_${index}`">
            {{item.name}}
          </div>
        </div>
        <!-- 级别 end -->

        <!-- 得分说明 开始 -->
        <div class="score_desc">
          <p>一般健康成年人的牙齿数量在28-32颗,您现有牙齿{{reportInfo.existingCnt||0}}颗,缺失牙齿{{reportInfo.defectCnt||0}}颗,智齿{{reportInfo.wisdomCnt||0}}颗(阻生智齿{{reportInfo.impactionCnt||0}}颗);</p>
          <p>患龋齿牙齿{{reportInfo.cariesCnt||0}}颗,患根尖周炎牙齿{{reportInfo.periodontitisCnt||0}}颗;</p>
          <p>经充填物修复的牙齿{{reportInfo.fillingsCnt||0}}颗,经根管填充修复的牙齿{{reportInfo.rootCanalCnt||0}}颗,经冠修复的牙齿{{reportInfo.crownCnt||0}}颗,种植体{{reportInfo.implantCnt||0}}颗;</p>
          <p v-if="reportInfo.alveolarBone">您的牙槽骨有骨吸收症状。</p>
        </div>
        <!-- 得分说明 end -->

      </div>
      <!-- 牙齿背景 开始 -->
      <img src="@/assets/images/pdf/score_teeth.png" class="score_teeth" alt="">
      <!-- 牙齿背景 end -->

      <div class="score_footer">
        <div class="desc_wrap plr40">
          请保持良好的口腔卫生习惯。建议每年在专业口腔机构定期进行口腔检查和口腔健康评估。
        </div>
        <footer-logo></footer-logo>
      </div>

    </div>
    <!-- 第二页 end -->

    <!-- 第三页 开始 -->
    <div class="single_page">
      <div class="inner_page plr40">
        <!-- 面包屑 开始 -->
        <bread-crumbs :name="reportInfo.name"></bread-crumbs>
        <!-- 面包屑 end -->

        <div class="title_wrap">
          <p>您的口腔全景片</p>
          <p>Your Oral Panorama</p>
        </div>

        <div class="panorama">
          <img :src="showPanorama(reportInfo.pics)" alt="" crossorigin="anonymous">
        </div>

      </div>
      <div class="score_footer">
        <footer-logo></footer-logo>
      </div>
    </div>
    <!-- 第三页 end -->

    <!-- 第四页 开始 -->
    <div class="single_page">
      <div class="inner_page plr40">
        <!-- 面包屑 开始 -->
        <bread-crumbs :name="reportInfo.name"></bread-crumbs>
        <!-- 面包屑 end -->

        <div class="title_wrap">
          <p>您的分析结果</p>
          <p>Your Analysis Results</p>
        </div>

        <div class="panorama panorama_result">
          <!-- <img :src="showPanorama(reportInfo.resultImage)" alt="" crossorigin="anonymous"> -->
          <img :src="showPanorama(reportInfo.pics)" alt="" crossorigin="anonymous">
          <div class="tag_line" :class="getToothClass(item)" v-for="(item,index) in reportInfo.items" :key="index" :style="getToothStyles(item)">
            <p class="desc"><span>{{showName(teethInfo[item.toothNum])}}</span></p>
            <div class="left_line"></div>
            <div class="top_line"></div>
          </div>
        </div>

      </div>
      <div class="score_footer">
        <footer-logo></footer-logo>
      </div>
    </div>
    <!-- 第四页 end -->

    <!-- 循环创建问题页面 开始 -->
    <template v-for="(item,index) in questionList">
      <div class="single_page" v-if="item.showFlag == 0" :key="index">
        <div class="inner_page question_page plr40">
          <!-- 面包屑 开始 -->
          <bread-crumbs :name="reportInfo.name"></bread-crumbs>
          <!-- 面包屑 end -->

          <div class="question_title">
            <div class="title_wrap">
              <p class="p1">您的口腔问题{{index+1}}：{{item.problem}}</p>
              <p class="p2">Your Oral Problem {{index+1}}: Alveolar Bone Resorption</p>
            </div>
            <div class="question_img">
              <img :src="showPanorama(item.pics)" alt="" crossorigin="anonymous">
            </div>
          </div>
          <div class="question_box">
            <div class="cell">检出问题：您的{{showTeeth(item)}}牙患有{{item.problem}}</div>
            <div class="cell" v-if="item.etiologyDefinition">病因及定义：{{item.etiologyDefinition}}</div>
            <div class="cell" v-if="item.consequence">引发后果：{{item.consequence}}</div>
            <div class="cell" v-if="item.imagingFeatures">影像表现：{{item.imagingFeatures}}</div>
            <div class="cell" v-if="item.treatmentMethod">治疗手段：{{item.treatmentMethod}}</div>
            <div class="cell" v-if="item.precaution">预防措施：{{item.precaution}}</div>
            <div class="cell" v-if="item.costReference">治疗费用参考：{{item.costReference}}元(单科)</div>
          </div>

        </div>
        <div class="score_footer">
          <footer-logo></footer-logo>
        </div>
      </div>
    </template>
    <!-- 循环创建问题页面 end -->

    <div class="single_page">
      <div class="inner_page plr40">
        <!-- 面包屑 开始 -->
        <bread-crumbs :name="reportInfo.name"></bread-crumbs>
        <!-- 面包屑 end -->

        <div class="title_wrap">
          <p>治疗方案参考</p>
          <p>Treatment Plan Reference</p>
        </div>
        <div class="teeth_wrap">
          <div class="teeth_box">
            <div class="cell_box cell_top_left_box">
              <div class="cell" :ref="`teeth_${item.label}`" v-for="(item,index) in teethTopLeftList" :key="`tf_${index}`">
                <div class="img_box">
                  <img :src="require(`@/assets/images/teeth/${item.icon}`)" alt="">
                </div>
                <div class="name">{{item.label}}</div>
                <div class="tag_line" :class="item.label == 18?'tag_top_first':''" v-if="showPlanName(methods[item.label])" :style="getStyles(item)">
                  <p class="desc"><span :style="{'background':styleList[item.label].background}">{{showPlanName(methods[item.label])}}</span></p>
                  <div class="left_line" :style="{'background':styleList[item.label].background}"></div>
                  <div class="top_line" :style="{'background':styleList[item.label].background}"></div>
                </div>
              </div>
            </div>
            <div class="cell_box cell_top_right_box">
              <div class="cell" :ref="`teeth_${item.label}`" v-for="(item,index) in teethTopRightList" :key="`tr_${index}`">
                <div class="img_box">
                  <img :src="require(`@/assets/images/teeth/${item.icon}`)" alt="">
                </div>
                <div class="name">{{item.label}}</div>
                <div class="tag_line" :class="item.label == 28?'tag_top_last':''" v-if="showPlanName(methods[item.label])" :style="getStyles(item)">
                  <p class="desc"><span :style="{'background':styleList[item.label].background}">{{showPlanName(methods[item.label])}}</span></p>
                  <div class="left_line" :style="{'background':styleList[item.label].background}"></div>
                  <div class="top_line" :style="{'background':styleList[item.label].background}"></div>
                </div>
              </div>
            </div>
          </div>

          <div class="teeth_box bottom_box">
            <div class="cell_box cell_bottom_left_box">
              <div class="cell" :ref="`teeth_${item.label}`" v-for="(item,index) in teethBottomLeftList" :key="`bf_${index}`">
                <div class="name">{{item.label}}</div>
                <div class="img_box">
                  <img :src="require(`@/assets/images/teeth/${item.icon}`)" alt="">
                </div>
                <div class="tag_line" :class="item.label == 48?'tag_bottom_first':''" v-if="showPlanName(methods[item.label])" :style="getStyles(item)">
                  <div class="left_line" :style="{'background':styleList[item.label].background}"></div>
                  <div class="top_line" :style="{'background':styleList[item.label].background}"></div>
                  <p class="desc"><span :style="{'background':styleList[item.label].background}">{{showPlanName(methods[item.label])}}</span></p>
                </div>
              </div>
            </div>
            <div class="cell_box cell_bottom_right_box">
              <div class="cell" :ref="`teeth_${item.label}`" v-for="(item,index) in teethBottomRightList" :key="`br_${index}`">
                <div class="name">{{item.label}}</div>
                <div class="img_box">
                  <img :src="require(`@/assets/images/teeth/${item.icon}`)" alt="">
                </div>
                <div class="tag_line" :class="item.label == 38?'tag_bottom_last':''" v-if="showPlanName(methods[item.label])" :style="getStyles(item)">
                  <div class="left_line" :style="{'background':styleList[item.label].background}"></div>
                  <div class="top_line" :style="{'background':styleList[item.label].background}"></div>
                  <p class="desc"><span :style="{'background':styleList[item.label].background}">{{showPlanName(methods[item.label])}}</span></p>
                </div>
              </div>
            </div>
          </div>

        </div>
        <div class="score_footer">
          <footer-logo></footer-logo>
        </div>
        <div class="consequence" v-if="reportInfo.consequence">
          <p>不及时治疗引发的后果：{{reportInfo.consequence}}</p>
        </div>

      </div>

    </div>

    <!-- 第五页 开始 -->
    <div class="single_page">
      <div class="inner_page plr40">
        <!-- 面包屑 开始 -->
        <bread-crumbs :name="reportInfo.name"></bread-crumbs>
        <!-- 面包屑 end -->

        <div class="title_wrap">
          <p>牙齿结构</p>
          <p>Tooth Structure</p>
        </div>

        <div class="teeth_science">
          <div class="cell">牙釉质：牙冠最外层的坚硬组织</div>
          <div class="cell">血管与神经：为牙齿提供营养与知觉</div>
          <div class="cell">牙本质：由牙本质小管组成的硬组织</div>
          <div class="cell">牙龈：覆盖牙根的软组织，为牙根提供支持与保护</div>
          <div class="cell">牙髓：包含血管与神经的柔软组织</div>
          <div class="cell">牙槽骨：覆盖牙根提供支持与保护</div>
        </div>

        <div class="teeth_science_img">
          <img src="@/assets/images/pdf/teeth.png" class="" alt="" />
        </div>

      </div>
      <div class="score_footer">
        <footer-logo></footer-logo>
      </div>
    </div>
    <!-- 第四页 end -->

    <!-- 最后一页 开始 -->
    <div class="single_page">
      <div class="inner_page company_box">
        <div class="company_profile">
          <img src="@/assets/images/pdf/bg2.png" alt="">
          <div class="profie">
            <span>ABOUT</span>
            <span>US</span>
            <span class="sp3">关于邦正口腔</span>
          </div>
        </div>

        <div class="profile_box">
          <p>邦正口腔是一家专注于口腔健康领域和AI技术应用的互联网公司!总部位于中国深圳,核心团队来自于腾讯、百度、3M等公司,公司在互联网健康领域和口腔行业深耕多年，洞察行业革新和前沿技术，通过整合口腔专家、口腔医院、供应链等资源，为患者提供更优质、更优惠、更透明的口腔健康服务，提升患者就诊体验！</p>
          <p>官方网站：http://www.lilikq.com</p>
          <p>官方公众号：邦正口腔</p>
        </div>

      </div>
      <div class="qrcode">
        <img src="@/assets/images/pdf/qrcode.png" alt="" />
        <p>官方公众号二维码</p>
      </div>

    </div>
    <!-- 最后一页 end -->

    <!-- 最后一页 开始 -->
    <div class="single_page last_page">
      <div class="last_content">
        <p class="p1">为患者提供更优质、更优惠、更透明的口腔健康服务</p>
        <p class="p2">TO PROVIDE PATIENTS WITH BETTER, MORE AFFORDABLE AND MORE TRANSPARENT ORAL HEALTH SERVICES</p>
      </div>
      <div class="last_footer">
        <div class="last_footer_logo">
          <img src="@/assets/images/pdf/logo_white.png" alt="">
          <div class="desc">
            <p class="p1">邦正口腔 | 互联网口腔健康服务平台</p>
            <p class="p2">专注于提升全民口腔健康水平</p>
          </div>
        </div>
      </div>
    </div>
    <!-- 最后一页 end -->

    <el-button type="primary" @click="createFile" :loading="loading" class="down_btn">下载PDF</el-button>

  </div>
</template>
<script>
import { BASEURL, GETREPORTINFO } from "@/http/report";
import { jsPDF } from "jspdf";
import html2canvas from "html2canvas";
import FooterLogo from "@/components/pdf/logo";
import BreadCrumbs from "@/components/pdf/breadcrumbs";
import moment from "moment";
export default {
  components: {
    FooterLogo,
    BreadCrumbs,
  },
  data() {
    return {
      loading: false,
      reportInfo: {},
      levelList: [
        { name: "极差", id: 1 },
        { name: "一般", id: 2 },
        { name: "合格", id: 3 },
        { name: "良好", id: 4 },
        { name: "优秀", id: 5 },
      ],
      level: 4,
      questionList: [],
      teethTopLeftList: [
        { label: "18", icon: "teeth_18.png", active: "teeth_active_18.png" },
        { label: "17", icon: "teeth_17.png", active: "teeth_active_17.png" },
        { label: "16", icon: "teeth_16.png", active: "teeth_active_16.png" },
        { label: "15", icon: "teeth_15.png", active: "teeth_active_15.png" },
        { label: "14", icon: "teeth_14.png", active: "teeth_active_14.png" },
        { label: "13", icon: "teeth_13.png", active: "teeth_active_13.png" },
        { label: "12", icon: "teeth_12.png", active: "teeth_active_12.png" },
        { label: "11", icon: "teeth_11.png", active: "teeth_active_11.png" },
      ],
      teethTopRightList: [
        { label: "21", icon: "teeth_21.png", active: "teeth_active_21.png" },
        { label: "22", icon: "teeth_22.png", active: "teeth_active_22.png" },
        { label: "23", icon: "teeth_23.png", active: "teeth_active_23.png" },
        { label: "24", icon: "teeth_24.png", active: "teeth_active_24.png" },
        { label: "25", icon: "teeth_25.png", active: "teeth_active_25.png" },
        { label: "26", icon: "teeth_26.png", active: "teeth_active_26.png" },
        { label: "27", icon: "teeth_27.png", active: "teeth_active_27.png" },
        { label: "28", icon: "teeth_28.png", active: "teeth_active_28.png" },
      ],
      teethBottomLeftList: [
        { label: "48", icon: "teeth_48.png", active: "teeth_active_48.png" },
        { label: "47", icon: "teeth_47.png", active: "teeth_active_47.png" },
        { label: "46", icon: "teeth_46.png", active: "teeth_active_46.png" },
        { label: "45", icon: "teeth_45.png", active: "teeth_active_45.png" },
        { label: "44", icon: "teeth_44.png", active: "teeth_active_44.png" },
        { label: "43", icon: "teeth_43.png", active: "teeth_active_43.png" },
        { label: "42", icon: "teeth_42.png", active: "teeth_active_42.png" },
        { label: "41", icon: "teeth_41.png", active: "teeth_active_41.png" },
      ],
      teethBottomRightList: [
        { label: "31", icon: "teeth_31.png", active: "teeth_active_31.png" },
        { label: "32", icon: "teeth_32.png", active: "teeth_active_32.png" },
        { label: "33", icon: "teeth_33.png", active: "teeth_active_33.png" },
        { label: "34", icon: "teeth_34.png", active: "teeth_active_34.png" },
        { label: "35", icon: "teeth_35.png", active: "teeth_active_35.png" },
        { label: "36", icon: "teeth_36.png", active: "teeth_active_36.png" },
        { label: "37", icon: "teeth_37.png", active: "teeth_active_37.png" },
        { label: "38", icon: "teeth_38.png", active: "teeth_active_38.png" },
      ],
      teethInfo: {},
      teethStyles: {},
      problemsInfo: {},
      colorList: {},
      styleList: {},
      methods: {},
    };
  },
  created() {},
  mounted() {
    // 不合格≤60
    // 60<合格≤70
    // 70<中等≤80
    // 80<良好≤90
    // 90<优秀

    this.getInfo();
  },
  methods: {
    // 获取报告详情
    getInfo() {
      let _this = this;
      let query = this.$route.query;
      GETREPORTINFO({ id: query.id }).then((res) => {
        let obj = res.data || {};
        let score = obj.oralCavityScore;
        let list = obj.items || [];
        let arr = [];
        let options = {};
        let problems = {};
        let styleList = {};
        let methods = {};
        list.map((k) => {
          arr = arr.concat(k.problems);
          options[k.toothNum] = k.problems || [];
          methods[k.toothNum] =
            k.methods ||
            [](k.problemIds || []).map((j) => {
              if (problems[j]) {
                let idx = problems[j].findIndex((h) => h == k.toothNum);
                if (idx < 0) {
                  problems[j].push(k.toothNum);
                }
              } else {
                problems[j] = [k.toothNum];
              }
            });
          //k.color = _this.randomColor();
          k.background = "#409EFF";
          k.color = "#fff";
          styleList[k.toothNum] = k;
        });
        console.log(problems);
        this.questionList = this.removeDuplicate(arr);
        this.reportInfo = obj;
        this.teethInfo = options;
        this.problemsInfo = problems;
        this.methods = methods;
        this.styleList = styleList;
        this.setLevel(score);
      });
    },

    // 生成PDF
    async createFile() {
      let _this = this;
      let orderList = document.getElementsByClassName("single_page");
      var doc = new jsPDF("", "pt", "a4");
      _this.loading = true;
      for (let i = 0, len = orderList.length; i < len; i++) {
        let target = orderList[i];
        await html2canvas(target, {
          logging: false,
          scale: 2,
          dpi: 200,
          useCORS: true,
          allowTaint: true,
        }).then((canvas) => {
          let img = canvas.toDataURL("image/jpeg", 1);
          let contentWidth = canvas.width;
          let contentHeight = canvas.height;

          let imgWidth = 595.28;
          let imgHeight = (595.28 / contentWidth) * contentHeight;
          doc.addImage(img, "JPEG", 0, 0, imgWidth, imgHeight);
          if (i < len - 1) {
            doc.addPage();
          }
        });
      }
      let pdfName = `${this.reportInfo.name}口腔健康评估报告${this.showTime(
        this.reportInfo.createdDate
      )}.pdf`;
      doc.save(pdfName);
      _this.loading = false;
    },

    // 展示全景片
    showPanorama(arr) {
      let path = "";
      if (typeof arr == "string") {
        path = arr;
      } else {
        path = arr && arr.length > 0 ? arr[0] : "";
      }
      let url = BASEURL + path;
      return url;
    },

    // 设置得分级别
    setLevel(score) {
      let level = 1;
      if (score > 90) {
        level = 5;
      }
      if (score <= 90 && score > 80) {
        level = 4;
      }

      if (score <= 80 && score > 70) {
        level = 3;
      }

      if (score <= 70 && score > 60) {
        level = 2;
      }
      this.level = level;
    },

    // 数组去重
    removeDuplicate(arr) {
      const newArr = [];
      arr.forEach((item) => {
        let idx = newArr.findIndex((k) => k.id == item.id);
        if (idx < 0 && item.showFlag == 0) {
          newArr.push(item);
        }
      });
      return newArr;
    },

    // 展示名称
    showName(list) {
      let str = "";
      if (!list || list.length <= 0) {
        return "";
      }
      let arr = [];
      list.map((k) => {
        arr.push(k.problem);
      });
      str = arr.toString();
      return str;
    },

    // 展示样式
    showStyles(row) {
      let o = this.reportInfo;
      let list = o.items || [];
      let m = list.find((k) => k.toothNum == row.label);
      let options = {};
      options.height = m.height / 2 + "px";
      options.width = m.width + "px";
      console.log(options);
      let color = this.randomColor();
      this.$set(this.colorList, row.label, color);
      return options;
    },

    // 随机样式颜色
    randomColor() {
      var color = "#";
      for (var i = 0; i < 6; i++)
        color += parseInt(Math.random() * 16).toString(16);
      return color;
    },

    // 展示线条颜色
    showLineStyles(id) {
      let options = this.colorList;
      let color = options[id];
      return { background: color };
    },

    // 格式化时间
    showTime(str) {
      if (!str) {
        return "";
      }
      let time = moment(str).format("yyyy年MM月DD日");
      return time;
    },

    // 展示牙齿
    showTeeth(row) {
      let names = [];
      let arr = this.problemsInfo[row.id] || [];
      let types = {
        1: "左上",
        2: "右上",
        3: "右下",
        4: "左下",
      };

      arr.map((k) => {
        let n = k.toString().split("");
        let m = types[n[0]] + n[1];
        names.push(m);
      });
      return names.toString();
    },

    // 动态设置样式
    getStyles(row) {
      
      let options = {};
      if (row.label % 3 == 0) {
        options.height = `110px`;
        options.top = `-110px`;
      }
      if (row.label % 3 == 2) {
        options.height = `100px`;
        options.top = `-100px`;
      }
      if (row.label % 3 == 1) {
        options.height = `90px`;
        options.top = `-90px`;
      }

      // 下排
      if (row.label > 30) {
        delete options.top;
      }

      

      return options;
    },

    //
    getToothStyles(row) {
      let o = this.reportInfo
      let num = 1030/512;
      let options = {};
      options.position = "absolute";
      options.width = row.width / num + "px";
      options.height = row.height / num + "px";
      options.top = (row.top-60) / num + "px";
      options.left = (row.left-o.leftWidth) / num + "px";

      return options;
    },

    // 获取牙齿定位class
    getToothClass(row) {
      let num = row.toothNum;
      if (num > 10 && num < 20) {
        return "tag_top_left_line";
      }

      if (num > 20 && num < 30) {
        return "tag_top_right_line";
      }

      if (num > 30 && num < 40) {
        return "tag_bottom_right_line";
      }

      if (num > 40) {
        return "tag_bottom_left_line";
      }
    },

    // 展示方案
    showPlanName(list) {
      console.log(list);
      if (!list || list.length <= 0) {
        return "";
      }
      let arr = [];
      list.map((k) => {
        arr.push(k.method);
      });
      return arr.toString();
    },
  },
};
</script>
<style lang="scss" scoped>
.down_btn {
  position: fixed;
  left: 10px;
  top: 50%;
}
@import "@/assets/style/preview.scss";
</style>